/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package project.jpdftools.pdfconverter;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import java.io.FileInputStream;
import java.util.logging.Level;
import javax.swing.filechooser.FileNameExtensionFilter;
import project.jpdfexport.constants.JPDFConst.TYPE;
import project.jpdftools.managers.LoggerManager;
import project.jpdftools.managers.other.FileUtil;

/**
 *
 * @author Mido
 */
public class PdfToText extends Converter {

    public PdfToText() {
        super();
        // set extensions
        this.setSourceExtensionFilter(new FileNameExtensionFilter("PDF Files (*.pdf)", "pdf"));
        this.setDestinationExtension(".txt");
        this.setUseAdvancedOptions(false);
        // use left-to-right languages as the default language
        this.setLanguageType(TYPE.left_to_right);
        // default font used
        this.setUseDefaultFont(true);
        // don't use document info
        this.setUseDocumentInfo(false);
        LoggerManager.getLogger().log(Level.INFO, "Pdf-to-text conversion selected.");
    }

    @Override
    public boolean convertFiles(String creator, String title, String author, String subject, String keywords, String font_path_name) {
        try {
            PdfReader reader = new PdfReader(new FileInputStream(this.getSource()));
            String text = "";
            // get pages number
            int pages = reader.getNumberOfPages();
            // extract the text from the pdf file
            for (int i = 0; i < pages; i++) {
                text += PdfTextExtractor.getTextFromPage(reader, i + 1);
            }
            // create a txt file with the read text
            new FileUtil().writeToFile(this.getDestination(), text, false, false);
            LoggerManager.getLogger().log(Level.INFO, "File converted successfully.");
            return true;
        } catch (Exception ex) {
            LoggerManager.getLogger().log(Level.SEVERE, "Error in file conversion. Message = {0}", project.jpdftools.toolkit.Toolkit.getStackTraceAsString(ex.getCause()));
            return false;
        }
    }
}
